package com.example.book.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.book.common.Result;
import com.example.book.entry.Cart;
import com.example.book.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private ICartService cartService;

//    根据用户id获取用户的购物车
    @GetMapping("/id={id}")
    public Result getUserCart(@PathVariable Integer id){
        List<Cart> userCart = cartService.getUserCart(id);
        return Result.success(userCart);
    }

//    根据用户id查询用户添加的购物车并实现分页
    @GetMapping("/page")
    public Result getCartPage(@RequestParam Integer pageNum,
                              @RequestParam Integer pageSize,
                              @RequestParam Integer id){
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
//        根据用户id查询用户添加的购物车
        queryWrapper.eq("user_id", id);
        Page<Cart> page = cartService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }

//    添加/修改购物车，
    @PostMapping("/addcart")
    public Result addCart(@RequestBody Cart cart){

        // 判断当前用户是否有相同的购物车
        Integer cartId = cart.getBookId();
        Integer userId = cart.getUserId();
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("book_id", cartId);
        queryWrapper.eq("user_id", userId);
        // 判断购物车里面是否已经有相同数据，如果有，就把数量加上去
        Cart one = cartService.getOne(queryWrapper);
        if(one != null){
            one.setBookNum(one.getBookNum() + cart.getBookNum());
            cartService.updateById(one);
            return Result.success();
        } else {
//            没查到数据，则新增一条
            cartService.saveOrUpdate(cart);
            return Result.success("success");
        }

    }

//    删除购物车
    @DeleteMapping("/{id}")
    public Result delCart(@PathVariable Integer id){
        cartService.removeById(id);
        return Result.success("删除成功");
    }

}
